<template>
  <transition name="confirm-fade">
    <div class="confirm" v-show="showFlag" @click.stop>
      <div class="confirm-wrapper">
        <div class='topoperate flex-start'>
          <div class='all_blue2'>地图选点</div>
          <div class='all_content'></div>
        </div>
        <div :id="randomId" class='l-map'></div>
        <div>
          <el-input clearable  v-show="detailsvisible" class='r-result' size="small" type="text" placeholder="请输入地址" :id="suggestId"  style="width:300px;" v-model="address_detail"></el-input>
        </div>
        <div class="operate">
          <div class="leftSide" style='float:left'>地址：{{address_detail2 ? address_detail2: '无'}}</div>
          <div class="rightSide">
            <el-button @click="hide">{{unableSet === true ? '关闭' : '取消'}}</el-button>
            <el-button type="primary" v-if="!unableSet" @click="confirm">确认</el-button>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'mapannotation',
  data () {
    return {
      unableSet: false,
      ruleForm: {
        longitude: '',
        latitude: ''
      },
      detailsvisible: false,
      options: [],
      address_detail: null, // 详细地址
      address_detail2: null, // 详细地址
      showFlag: false,
      resultObj: {}, // 坐标逆解析结果对象(根据经纬度获取地址)
      curPoint: {}, // 当前选中的坐标经纬度
      scrollTop: null,
      scrollLeft: null,
      randomId: '',
      suggestId: ''
    };
  },
  created () {
    this.randomId = this.randomString()
    this.suggestId = this.randomString2()
  },
  mounted () {
  },
  methods: {
    info () {
      this.detailsvisible = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.show();
        }, 1000);
      });
    },
    show () {
      document.body.style.overflow = 'hidden'
      this.scrollTop = document.documentElement.scrollTop
      this.scrollLeft = document.documentElement.scrollLeft
      window.scrollTo(0, 0)
      this.showFlag = true
      this.$nextTick(() => {
        setTimeout(() => {
        // 初始化地图
          var th = this
          // 第一次点开地图弹框，进行地图的实例化
          var map = new BMap.Map(this.randomId, { enableMapClick: false });
          // 初始化地图,设置中心点坐标，
          if (
            this.defaultPoint &&
            this.defaultPoint.lng &&
            this.defaultPoint.lat
          ) {
            map.clearOverlays()
            let point = new BMap.Point(
              this.defaultPoint.lng,
              this.defaultPoint.lat
            )
            map.centerAndZoom(point, 12)
            map.enableScrollWheelZoom(); // 启动鼠标滚轮操作
            let marker = new BMap.Marker(point)
            map.addOverlay(marker)
            this.address_detail2 = this.defaultPoint.address
          } else {
            let point = new BMap.Point(116.401947, 39.915272); // 创建点坐标
            map.centerAndZoom(point, 12);
            map.enableScrollWheelZoom(); // 启动鼠标滚轮操作
            // let marker = new BMap.Marker(point)
            // map.addOverlay(marker)
          }
          this.address_detail = ''
          var ac = new BMap.Autocomplete(
            // 建立一个自动完成的对象
            {
              'input': this.suggestId,
              'location': map
            }
          )
          var myValue
          ac.addEventListener('onconfirm', function (e) {
          // 鼠标点击下拉列表后的事件
            var _value = e.item.value; // 获取选中的地址信息
            myValue = _value.province + _value.city + _value.district + _value.street + _value.business; // 拼接成具体地址
            th.address_detail = th.address_detail2 = myValue
            setPlace();
          });
          function setPlace () {
            map.clearOverlays(); // 清除地图上所有覆盖物
            function myFun () {
              if (local.getResults().getPoi(0)) {
                th.curPoint = local.getResults().getPoi(0).point; // 获取第一个智能搜索的结果
                map.centerAndZoom(th.curPoint, 12);
                map.addOverlay(new BMap.Marker(th.curPoint)); // 添加标注
              } else {}
            }
            var local = new BMap.LocalSearch(map, { // 智能搜索
              onSearchComplete: myFun
            });
            local.search(myValue);
          }
          // 测试输出坐标（指的是输入框最后确定地点的经纬度）
          if (!this.detailsvisible) {
            map.addEventListener('click', function (e) {
              map.clearOverlays();
              th.curPoint = new BMap.Point(e.point.lng, e.point.lat)
              let marker = new BMap.Marker(th.curPoint)
              map.addOverlay(marker)
              var geoc = new BMap.Geocoder();
              var pt = e.point;
              geoc.getLocation(pt, function (rs) {
                var addComp = rs.addressComponents;
                th.address_detail2 = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
              });
            })
          }
          var geoc = new BMap.Geocoder();
          map.addEventListener('click', function (e) { // 给地图添加点击事件
            map.clearOverlays();
            // 创建标注位置
            th.curPoint = new BMap.Point(e.point.lng, e.point.lat)
            let marker = new BMap.Marker(th.curPoint)
            map.addOverlay(marker); // 将标注添加到地图中
            var pt = e.point;
            geoc.getLocation(pt, function (rs) {
              var addComp = rs.addressComponents;
              th.address_detail2 = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
            });
          })
        }, 500);
      })
    },
    hide () {
      var map = new BMap.Map(this.randomId, { enableMapClick: false });
      this.showFlag = false
      document.body.style.overflow = 'auto'
      if (this.scrollTop !== null && this.scrollLeft !== null) {
        window.scrollTo(this.scrollLeft, this.scrollTop)
      }
      this.address_detail = ''
      if (!this.resultObj.lng && !this.resultObj.lat) {
        map.clearOverlays()
        if (
          this.defaultPoint &&
          this.defaultPoint.lng &&
          this.defaultPoint.lat
        ) {
          this.drawDefaultPoint()
        } else {
          let center = new BMap.Point(116.398395, 39.132039)
          map.centerAndZoom(center, 12)
        }
      }
    },
    confirm () {
      if (!this.curPoint.lng && !this.curPoint.lat) {
        this.$message({
          message: '请在地图上标记位置点',
          type: 'info'
        })
        return
      }
      // 给经纬度获取详细地址
      this.geoc = new BMap.Geocoder()
      this.geoc.getLocation(this.curPoint, res => {
        this.showFlag = false
        document.body.style.overflow = 'auto'
        if (this.scrollTop !== null && this.scrollLeft !== null) {
          window.scrollTo(this.scrollLeft, this.scrollTop)
        }
        if (res !== null) {
          this.resultObj = {
            address: this.address_detail2,
            lng: res.point.lng,
            lat: res.point.lat,
            addressComponents: res.addressComponents // 省市县
          }
          this.$emit('getLocation', this.resultObj)
        } else {
          this.$message({
            message: '未能获取位置详细信息',
            type: 'warning'
          })
          if (this.address_detail) {
            this.resultObj = {
              address: this.address_detail
            }
          } else {
            this.resultObj = this.curPoint
          }
          this.$emit('getLocation', this.resultObj)
        }
      })
    },
    drawDefaultPoint () {
      var map = new BMap.Map(this.randomId, { enableMapClick: false });
      map.clearOverlays()
      this.curPoint = new BMap.Point(
        this.defaultPoint.lng,
        this.defaultPoint.lat
      )
      map.centerAndZoom(this.curPoint, 12)
      let marker = new BMap.Marker(this.curPoint)
      map.addOverlay(marker)
      this.address_detail2 = this.defaultPoint.address // 详情时从父组件传过来的地址
    },
    // 生成随机id数（因为一个页面可能多次用到地图组件，保证其地图加载时能找到唯一的id）
    randomString () {
      var $chars = 'ZM6fZihEjR1YhHvVBlQfzlbeReZZ1wC5'
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < 32; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    randomString2 () {
      var $chars = 'ZM6fZihEjR1YhHvVBlQfzlbeReZZ1wC5'
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < 32; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    clearResult () {
      this.resultObj = {}
    }
  }
}
</script>
<style scoped>
.login-btn{margin-top: 20px;}
.confirm {position: fixed;left: 0;right: 0;top: 0;bottom: 0;z-index: 990;background-color: rgba(0, 0, 0, 0.3);padding: 40px 120px;}
.confirm.confirm-fade-enter-active {animation: confirm-fadein 0.3s;}
.confirm .confirm-wrapper {position: relative;width: 100%;height: 100%;z-index: 222;background: #fff;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);}
.confirm .confirm-wrapper .topoperate {position: absolute;height: 50px;width: 100%;top: 0;padding: 10px 20px;background: #fff;z-index: 99;}
.confirm .confirm-wrapper .operate {position: absolute;width: 100%;bottom: 0;padding: 10px 20px;background: #fff;text-align: center;}

.confirm .confirm-wrapper .operate .leftSide {float: left;line-height: 40px;}
.confirm .confirm-wrapper .operate .rightSide {float: right;}
.l-map {width: 98%;text-align: center;margin: 0 auto;height: 100%;}
.r-result {width:340px;z-index: 999;position: fixed;top: 110px;left: 150px;}
@keyframes confirm-fadein {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>
<style>
/* 关键字下拉框 */
.tangram-suggestion-main {
  z-index: 9999 !important;
}
/* 去掉坐下面默认百度logo版权 */
.BMap_cpyCtrl {
  display:none;
}
.anchorBL{
  display:none;
}
/* 标题样式 */
.all_blue2{
  border-left: 3px solid #6ab2ff;
  margin-right: 10px;
  padding: 0 5px;
}
</style>
